package com.example.demo.controller;


import com.example.demo.entity.QuestionBank;
import com.example.demo.entity.User;
import com.example.demo.service.IQuestionBankService;
import com.example.demo.utils.AjaxJson;
import com.example.demo.utils.UserContext;
import com.example.demo.vo.QuestionBankVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 题库表 前端控制器
 * </p>
 *
 * @author
 * @since 2025-11-10
 */
@RestController
@RequestMapping("/question-bank")
public class QuestionBankController {

    @Autowired
    private IQuestionBankService questionBankService;

    @RequestMapping("/add")
    public AjaxJson add(@RequestBody QuestionBankVo questionBank) {
        return questionBankService.add(questionBank);
//        return questionBankService.save(questionBank) ? AjaxJson.getSuccess("添加成功") : AjaxJson.getError("添加失败");
    }

    // TODO 应该对cookie里面的用户做一个教师题库关联查询以判断是不是本人的题
    @RequestMapping("/delete")
    public AjaxJson delete(@RequestParam Integer questionId) {
        return questionBankService.removeById(questionId) ? AjaxJson.getSuccess("删除成功") : AjaxJson.getError("删除失败");
    }

    @RequestMapping("/update")
    public AjaxJson update(@RequestBody QuestionBank questionBank) {
        return questionBankService.updateById(questionBank) ? AjaxJson.getSuccess("修改成功") : AjaxJson.getError("修改失败");
    }

    @RequestMapping("/query")
    public AjaxJson query() {
        //获取对应教师的题库
        List<QuestionBankVo> questionBanks = questionBankService.find();
        return AjaxJson.getPageData((long) questionBanks.size(), questionBanks);
    }

    @RequestMapping("/query/id")
    public AjaxJson query(@RequestParam Integer id) {
        return AjaxJson.getSuccessData(questionBankService.getById(id));
    }

    @RequestMapping("/updata/teacherId")
    public AjaxJson updataTeacherId(@RequestBody QuestionBank questionBank) {
        // 从线程中获取到用户信息user
        User user = UserContext.getCurrentUser();
        if (user == null || (user.getRoleId() != 1 && user.getRoleId() != 2)) {
            return AjaxJson.getNotJur("权限不足");
        } else {
            Integer userId = user.getUserId();
            return questionBankService.updataTeacherId(questionBank, userId);
        }

    }



}